package com.js.data.dtmg.quartz;

import com.js.data.dtmg.entity.DtTask;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author hh
 * @since 2024-07-13
 */

@Slf4j
@Component
public class QuartzJob {

    @Resource
    private Scheduler scheduler;

    final String QZ_JOB_GROUP_NAME = "JOB_GROUP_NAME_TASK";
    /**
     * 消息定时任务触发器组名
     */
    final String QZ_TRIGGER_GROUP_NAME = "TRIGGER_GROUP_NAME_TASK";

    /**
     * 添加一个单次执行的定时任务
     *
     * @param quartzModel {@link QuartzJobModule}
     */
    private void addQuartzJob(QuartzJobModule quartzModel, Class<? extends Job> jobClass) {
        try {
            //添加一个job任务
            JobDetail job = JobBuilder.newJob(jobClass)
                    .withIdentity(quartzModel.getJobName(), QZ_JOB_GROUP_NAME)
                    .setJobData(quartzModel.getJobDataMap()).build();
            //添加一个触发器
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(quartzModel.getTriggerName(), QZ_TRIGGER_GROUP_NAME)
                    .startNow()
                    .withSchedule(CronScheduleBuilder.cronSchedule(quartzModel.getCron()))
                    .build();
            scheduler.scheduleJob(job, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (SchedulerException e) {
            log.error("Add quartz job error, jobName = {}", quartzModel.getJobName());
        }
    }


    /**
     * 移除一个任务
     *
     * @param jobName          任务名称
     * @param triggerName      触发器名称
     */
    private void removeJob(String jobName, String triggerName) {
        TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, QZ_TRIGGER_GROUP_NAME);
        JobKey jobKey = JobKey.jobKey(jobName, QZ_JOB_GROUP_NAME);
        try {
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(jobKey);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 增加定时任务
     * @param task 任务信息
     */
    public void addTaskQuartzJob(DtTask task) {
        String name = "task_schedule_" + task.getId();
        QuartzJobModule jobModule = new QuartzJobModule();
        jobModule.setJobName(name);
        jobModule.setTriggerName(name);
        jobModule.setCron(task.getCron());
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("task", task);
        jobModule.setJobDataMap(jobDataMap);
        addQuartzJob(jobModule, TaskJobDetail.class);
    }

    public void removeTaskQuartzJob(Long taskId) {
        String name = "task_schedule_" + taskId;
        removeJob(name,name);
    }
}
